import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from PIL import Image, ImageTk
import sqlite3
import os
from datetime import datetime
import glob


def set_tags(selected_comics, cursor):
    if not selected_comics:
        messagebox.showwarning("警告", "请先选择一个漫画！")
        return
    
    comic_id = next(iter(selected_comics))
    
    # 获取当前标签
    cursor.execute("SELECT tag_name FROM comic_tags WHERE comic_id=?", (comic_id,))
    current_tags = {row[0] for row in cursor.fetchall()}
    
    # 创建标签窗口
    tag_win = tk.Toplevel(self.root)
    tag_win.title("设置标签")
    tag_win.geometry("400x300")
    
    # 常用标签
    cursor.execute("SELECT name FROM tags ORDER BY id DESC LIMIT 10")
    common_tags = [row[0] for row in self.cursor.fetchall()]
    
    tag_frame = tk.Frame(tag_win, padx=10, pady=10)
    tag_frame.pack(fill="both", expand=True)
    
    tk.Label(tag_frame, text="添加标签:").pack(anchor="w", pady=(0, 5))
    
    tag_entry = tk.Entry(tag_frame, width=30)
    tag_entry.pack(fill="x", pady=(0, 10))
    tag_entry.focus()
    
    # 常用标签区域
    if common_tags:
        tk.Label(tag_frame, text="常用标签:").pack(anchor="w", pady=(0, 5))
        
        common_frame = tk.Frame(tag_frame)
        common_frame.pack(fill="x", pady=(0, 10))
        
        for tag in common_tags:
            btn = tk.Button(common_frame, text=tag, 
                            command=lambda t=tag: tag_entry.insert(tk.END, t + ","))
            btn.pack(side="left", padx=5)
    
    # 当前标签区域
    tk.Label(tag_frame, text="当前标签:").pack(anchor="w", pady=(0, 5))
    
    current_frame = tk.Frame(tag_frame)
    current_frame.pack(fill="x", pady=(0, 10))
    
    for tag in current_tags:
        tag_frame = tk.Frame(current_frame, relief="groove", bd=1, padx=5, pady=2)
        tag_frame.pack(side="left", padx=5)
        
        tk.Label(tag_frame, text=tag).pack(side="left")
        tk.Button(tag_frame, text="×", command=lambda t=tag: self.remove_tag(tag_win, comic_id, t), 
                width=2).pack(side="left", padx=(5, 0))
    
    # 按钮区域
    btn_frame = tk.Frame(tag_frame)
    btn_frame.pack(fill="x", pady=10)
    
    tk.Button(btn_frame, text="保存", 
                command=lambda: self.save_tags(tag_win, comic_id, tag_entry.get(), current_tags)).pack(side="right", padx=5)
    tk.Button(btn_frame, text="取消", command=tag_win.destroy).pack(side="right", padx=5)